package com.misty.blog.controller.blogController;

import com.misty.auth.component.LoginUser;
import com.misty.blog.bean.param.ComSaveParam;
import com.misty.blog.service.MessageService;
import com.misty.common.bean.Result;
import com.misty.common.constants.ResultEnum;
import com.misty.dao.domain.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/fore/message")
@PreAuthorize("hasAuthority('message')")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @PreAuthorize("hasAuthority('fore/message')")
    @PostMapping("/save")
    public Result<?> save(@RequestBody ComSaveParam param){

//        查询当前登录用户ID
        LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userId = null;
        if(param.getUsername().equals(principal.getUsername())){
            userId = principal.getUser().getId();
        }
        //保存回复
        Message message = new Message();
        message.setCommentId(param.getCommentId())
                .setUserId(userId)
                .setToUserId(param.getToUserId())
                .setContent(param.getContent())
                .setCreateTime(LocalDateTime.now())
                .setUpdateTime(LocalDateTime.now());
        boolean save = messageService.save(message);
        if(!save){
            return Result.error("保存回复失败！");
        }
        return Result.success("保存回复成功！");
    }


    @PreAuthorize("hasAuthority('fore/message')")
    @DeleteMapping("/delete")
    @Transactional(transactionManager = "mistyTransactionManager")
    public Result<?> messageDelete(@RequestParam Integer id){
        //删除评论
        boolean removeById = messageService.removeById(id);
        if(!removeById){
            return Result.error("删除回复失败！");
        }
        return Result.success("删除回复成功！");
    }
}
